package com.example.死信队列;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 死信队列
 */
@Configuration
public class DeadLetterConfig {
    //死信队列
    public static final String DEAD_LETTER_QUEUE = "dead_letter_queue";
    //死信交换机
    public static final String DEAD_LETTER_EXCHANGE = "dead_letter_exchange";

    //普通队列
    public static final String MSG_LETTER_QUEUE = "msg_letter_queue";
    //普通交换机
    public static final String MSG_LETTER_EXCHANGE = "msg_letter_exchange";

    @Bean
    Queue deadLetterQueue() {
        return new Queue(DEAD_LETTER_QUEUE, true, false, false);
    }

    @Bean
    Queue msgLetterQueue() {
        Map<String, Object> ags = new HashMap<>();
        //设置过期时间为0 立马过期
        ags.put("x-message-ttl", 0);
        //设置此队列的消息过期后进入到的死信交换机
        ags.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        //设置此队列的消息过期后进入到的死信队列
        ags.put("x-dead-letter-routing-key", DEAD_LETTER_QUEUE);
        return new Queue(MSG_LETTER_QUEUE, true, false, false, ags);
    }

    @Bean
    DirectExchange deadLetterExchange() {
        return new DirectExchange(DEAD_LETTER_EXCHANGE, true, false);
    }

    @Bean
    DirectExchange msgLetterExchange() {
        return new DirectExchange(MSG_LETTER_EXCHANGE, true, false);
    }

    @Bean
    Binding deadBinding() {
        return BindingBuilder
            .bind(deadLetterQueue()).to(deadLetterExchange()).with(DEAD_LETTER_QUEUE);
    }

    @Bean
    Binding msgBinding() {
        return BindingBuilder
            .bind(msgLetterQueue()).to(msgLetterExchange()).with(MSG_LETTER_QUEUE);
    }
}
